import React, { useState, useEffect, Fragment } from 'react';
import { Tabs, Card, Table, Row, Col, Select, Button, Typography, Popover, Icon } from 'antd';
import { connect } from 'dva';
import moment from 'moment';
import _ from 'lodash';
import { handlerApprovalStatusColor } from '@/utils/publicFunction';
import AuthorizedButton from '@/components/AuthorizedButton';
import PageEmpty from '@/components/PageEmpty';
import { showConfirm } from '@/utils/utils';
import {
  CONSTANT_TAB_KEY1, // 投资正式版
  CONSTANT_TAB_KEY2, // 调整版
  CONSTANT_TAB_KEY3, // 实际版
  CONSTANT_EMPTYMSG1, // loading
  CONSTANT_EMPTYMSG3, // 空数据
  CONSTANT_VERSIONSTATUS, //版本状态
} from '../utils/constant';
import AdjustmentEditTable from './AdjustmentEditTable';
import * as request from '../utils/request';
import { router } from 'umi';
import { goodsApprovedViewUsingGET } from '@/services/ValueApprovelMgr';
const { Text } = Typography;
const { Option } = Select;

const Page = props => {
  const {
    dispatch,
    versionList,
    versionActive,
    match: { params },
    activeKey,
    edit,
    showApproveBtn,
  } = props;

  const [versionId, setVersionId] = useState('');
  const [data, setData] = useState([]);
  const [columns, setColumns] = useState([]);
  const [loading, setLoading] = useState(true);
  const [delLoading, setDelLoading] = useState(false);
  const [appovalLoading, setAppovalLoading] = useState(false);

  // 获取数据方法（表格 data 和 columns）
  const getData = async id => {
    if (!loading) setLoading(true);
    const { columns, data } = await request.getAdjustmentData(id);
    setData(data);
    setColumns(
      columns.map((tar, index) => {
        if (index === 0) return tar;
        return {
          ...tar,
          render: text => `${text}%`,
        };
      }),
    );
    setLoading(false);
    return;
  };

  // 整体刷新（获取版本列表=>获取表格数据）
  const refreshData = () => {
    const query = {
      projectId: params.project,
      versionType: CONSTANT_TAB_KEY2,
    };
    dispatch({
      type: 'PayBackModulus/getVersionsList',
      payload: query,
      callback: firstVersion => {
        if (firstVersion) {
          setVersionId(firstVersion.id);
          getData(firstVersion.id);
          showApproveBtn();
          return;
        }
        setLoading(false);
      },
    });
  };

  useEffect(() => {
    refreshData();
  }, [props.match.params.project]);

  // 版本切换
  const changeVersion = id => {
    const index = versionList.findIndex(tar => {
      return tar.id === id;
    });
    dispatch({
      type: 'PayBackModulus/save',
      payload: { versionActive: versionList[index] },
    });
    setVersionId(id);
    getData(id);
  };

  // 删除版本
  const delVersion = ({ id }) => {
    showConfirm(
      async () => {
        setDelLoading(true);
        const res = await request.deleteVersion(id);
        setDelLoading(false);
        if (res) refreshData();
      },
      `确认删除调整版的当前版本的回款系数吗？`,
      '删除后不可恢复，请谨慎操作',
    );
  };

  // 版本信息
  const versionDetail = detail => (
    <Fragment>
      <div style={{ margin: '0 0 10px 0' }}>
        <h4>基本信息</h4>
        <Row type="flex" justify="space-between" style={{ width: '500px' }} gutter={[0, 5]}>
          <Col span={12}>
            <span>{`版本名称 : 调整版${detail.versionNum}
          ${
            detail.approvalTime ? `-${moment(detail.approvalTime).format('YYYYMMDD')}` : ''
          }`}</span>
          </Col>
          <Col span={12}>
            <span>{`创建人 : ${detail.createUser}`}</span>
          </Col>
          <Col span={12}>
            <span>{`创建时间 : ${moment(detail.createTime).format('YYYY-MM-DD HH:mm:ss')}`}</span>
          </Col>
          <Col span={12}>
            <span>{`创建方式 : ${
              detail.versionCreate === 'automatic_create'
                ? '自动创建'
                : detail.versionCreate === 'manual_create'
                ? '手动创建'
                : ''
            }`}</span>
          </Col>
          {detail.updateTime && (
            <Col span={12}>
              <span>{`更新时间 : ${moment(detail.updateTime).format('YYYY-MM-DD HH:mm:ss')}`}</span>
            </Col>
          )}
        </Row>
      </div>
    </Fragment>
  );

  // 查看审批
  const handlerViewApproved = () => {
    setAppovalLoading(true);
    const parameters = {
      versionId,
    };
    goodsApprovedViewUsingGET({ params: parameters }).then(data => {
      if (data && data.code * 1 === 1 && data.data.status * 1 === 1) {
        window.open(`${data.data.url}`);
      }
      setAppovalLoading(false);
    });
  };

  return (
    <>
      {loading ? (
        <PageEmpty emptyTitle={CONSTANT_EMPTYMSG1} />
      ) : versionList.length === 0 ? (
        <PageEmpty emptyTitle={CONSTANT_EMPTYMSG3} />
      ) : (
        <>
          <Row type="flex" justify="space-between" align="middle" style={{ marginBottom: 10 }}>
            {versionActive && (
              <Col>
                <Select
                  size="small"
                  // onChange={value => {
                  //   router.replace(
                  //     `/ValueManage/PriceManage/${params.level1}/${params.level2}/${params.project}/${params.stage}/${params.category}/${value}`,
                  //   );
                  // }}
                  onChange={changeVersion}
                  dropdownMatchSelectWidth={false}
                  className="version-select"
                  value={versionId}
                >
                  {versionList.map(tar => (
                    <Option key={tar.id} value={tar.id}>
                      调整版{tar.versionNum}
                      {tar.approvalTime &&
                        tar.versionState === 'success_approved' &&
                        `-${moment(tar.approvalTime).format('YYYYMMDD')}`}
                    </Option>
                  ))}
                </Select>
                <Text className="version-status" strong>
                  &ensp;
                  <i
                    className="dots"
                    style={{
                      background: handlerApprovalStatusColor(versionActive.versionState),
                    }}
                  />
                  {CONSTANT_VERSIONSTATUS[versionActive.versionState]}&ensp;
                </Text>
                <Popover
                  content={versionDetail(versionActive)}
                  title="版本信息"
                  trigger="hover"
                  placement="bottomLeft"
                >
                  <Button style={{ color: '#4f84ff', border: 'solid 1px #fff' }}>
                    <Icon
                      type="snippets"
                      style={{
                        color: '#fff',
                        background: 'rgba(255, 141, 26, 1)',
                      }}
                    />
                  </Button>
                </Popover>
              </Col>
            )}
            <Col>
              <Row gutter={[5, 0]} type="flex" justify="space-between" align="middle">
                {(versionActive.versionState === 'not_prepared' ||
                  versionActive.versionState === 'organization' ||
                  versionActive.versionState === 'examined_approved' ||
                  versionActive.versionState === 'failure_approved') && (
                  <Col>
                    <AuthorizedButton authority="business_payBackModulus_editAdjustment">
                      <Button type="primary" onClick={() => edit(versionActive)}>
                        编辑
                      </Button>
                    </AuthorizedButton>
                  </Col>
                )}
                {(versionActive.versionState === 'examined_approved' ||
                  versionActive.versionState === 'approved' ||
                  versionActive.versionState === 'failure_approved' ||
                  versionActive.versionState === 'success_approved') && (
                  <AuthorizedButton authority="business_payBackModulus_viewApproved">
                    <Button
                      style={{ marginRight: 5 }}
                      className="yellow-button"
                      onClick={handlerViewApproved}
                      loading={appovalLoading}
                    >
                      查看审批
                    </Button>
                  </AuthorizedButton>
                )}
                {(versionActive.versionState === 'not_prepared' ||
                  versionActive.versionState === 'organization') && (
                  <Col>
                    <AuthorizedButton authority="business_payBackModulus_deleteAdjustment">
                      <Button loading={delLoading} onClick={() => delVersion(versionActive)}>
                        删除
                      </Button>
                    </AuthorizedButton>
                  </Col>
                )}
                <Col>
                  <AuthorizedButton authority="business_payBackModulus_approvedRecord">
                    <Button
                      onClick={() =>
                        router.push(
                          `/OperatingPlan/PayBackModulus/ProjectValue/${props.match.params.project}`,
                        )
                      }
                    >
                      审批记录
                    </Button>
                  </AuthorizedButton>
                </Col>
              </Row>
            </Col>
          </Row>
          <AdjustmentEditTable dataSource={data} columns={columns} />
        </>
      )}
    </>
  );
};

export default connect(state => ({
  // versionList: state.PayBackModulus.versionList,
  // versionActive: state.PayBackModulus.versionActive,
}))(Page);
